package com.fingard.dsp.bank.directbank.vbao01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.SingleDKRequest;
import com.vbao.service.trade.bean.request.SingleQueryRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.TradeCodeEnum;

import com.fingard.FGBiz;

public class VBAO01RealTime extends VBAO01Base implements IRealTime {
	@Override
	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail retDetail = new RetAtsSglDetail();

		ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
		if (actItem == null) {
			retDetail.respCode = "0";
			retDetail.respInfo = "未找到账号:[" + p_req9108.singleDetail.recAct + "]对应的商户配置信息";
			retDetail.reqSeqID = p_req9108.singleDetail.askNumber;
			retDetail.transState = PaymentState.FAIL_Payment;
			retDetail.payInfoCode = FailCode.E9981;
			retAts.writeRetDetail(retDetail);
			return retAts;
		}

		SingleDKRequest singleRecRequest = new SingleDKRequest();

		singleRecRequest.setVersion("6.0");
		singleRecRequest.setInputCharset(getCharset());
		singleRecRequest.setSignType("MD5");
		singleRecRequest.setCustomerNo(actItem.merchantId);

		String goodNo = "";
		boolean useEachGoodNo = getBankConfig().getValueAsBool("isUseEachGoodNo");
		if (useEachGoodNo) {
			goodNo = actItem.goodNo;
		} else {
			goodNo = getBankConfig().getValueAsString("GoodNo");
		}
		if (StringHelper.isNullOrEmpty(goodNo)) {
			WriteBankLogLn("配置文件缺失'GoodNo'配置或'GoodNo'映射错误!");
		}
		singleRecRequest.setGoodNo(goodNo);

//		singleRecRequest.setGoodNo(getBankConfig().getValueAsString("GoodNo"));
		singleRecRequest.setActName(p_req9108.singleDetail.recName);
		singleRecRequest.setActId(p_req9108.singleDetail.recAct);
		singleRecRequest.setActLineCode(p_req9108.singleDetail.cnapsCode);
		singleRecRequest.setOrderNo(p_req9108.singleDetail.askNumber);
		singleRecRequest.setOrderAmount(p_req9108.singleDetail.payAmount);
		singleRecRequest.setCertType(convertCertTypeToBank(p_req9108.singleDetail.certType));
		singleRecRequest.setCertId(p_req9108.singleDetail.certNum);

		// 1 折 2 借记卡 3 贷记卡 4 准贷记卡
		String cardType = p_req9108.singleDetail.cardType;
		if (cardType.equals("3") || cardType.equals("4")) {
			singleRecRequest.setBankCardType("2");
			singleRecRequest.setMobile(p_req9108.singleDetail.cellPhone);
			singleRecRequest.setCreditValid(p_req9108.singleDetail.expiredDate);
			singleRecRequest.setCreditCvv2(p_req9108.singleDetail.cvv2);
		} else if (cardType.equals("1")) {
			singleRecRequest.setBankCardType("1");//折
		} else {
			singleRecRequest.setBankCardType("0");// 卡
		}

		String bankCode = p_req9108.singleDetail.payBankCode;
		singleRecRequest.setBankCode(getBankConfig().getMapValueByKey("BankCodeMapping", bankCode));

		singleRecRequest.setBankCardNo(p_req9108.singleDetail.payAct);
		singleRecRequest.setBankCardName(p_req9108.singleDetail.payName);
		singleRecRequest.setProductName(p_req9108.singleDetail.askNumber);
		WriteBankLogLn2("初始化VbaoChargeSystemHandler");
		Date startTime = new Date();
		VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();
		
		double timeSpan = DateHelper.getDifferSecs(new Date(), startTime);
		if(timeSpan>=0.5){
			WriteBankLogAndLimit("初始化VbaoChargeSystemHandler耗时"+Format.DecimalAmtFormat.format(timeSpan)+"秒");
		}
		TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler.creatRequestXml(singleRecRequest,actItem.saltKey,getCharset(),TradeCodeEnum.SINGLE_DK.getCode());
		timeSpan = DateHelper.getDifferSecs(new Date(), startTime);
		if(timeSpan>=0.8){
			WriteBankLogAndLimit("初始化VbaoChargeSystemHandler+creatRequestXml总耗时"+Format.DecimalAmtFormat.format(timeSpan)+"秒");
		}
		WriteBankLogLn2("发送微保请求报文明文:" + tradeRequestXml.getOriRequestXml());
		WriteBankLogStep2(tradeRequestXml.getRequestXml());

		if(tradeRequestXml.getErrMsg() == null) {
			String reqURL = bankFront.getUrl("9108");
			WriteBankLogLn2("实时收款提交服务地址: " + reqURL);

			// 发送银行并获取返回
			String returnDKPayxml = vbaoChargeSystemHandler.http(reqURL,tradeRequestXml.getRequestXml(),getCharset());
			WriteBankLogLn2("微保返回报文密文:" + returnDKPayxml);

			if(returnDKPayxml != null) {
				try {
					String returnOriDKPayxml = Base64vbao.decode(returnDKPayxml,getCharset());
					//returnOriDKPayxml = new String(returnOriDKPayxml.getBytes(),getCharset());
					WriteBankLogStep3(returnOriDKPayxml);

					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(returnOriDKPayxml, tmpSbMsg);

					if (tmpBkReader != null) {
						retDetail.respCode = "0";
						retDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");

						String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
						if (tmpReturnCode.equals("T")) {
							retDetail.transAmt = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderAmount");
							retDetail.transState = tmpReturnCode + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode") + "+" + tmpBkReader.getFirstText("/TResponse/OrderInfo/PayStatus");
							retDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
							retDetail.reqSeqID = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderNo");
						} else {
							String errorCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
							retDetail.transState = tmpReturnCode + "+" + errorCode;
							retDetail.payInfoCode = errorCode;
							retDetail.reqSeqID = p_req9108.singleDetail.askNumber;
						}
					} else {
						retDetail.respCode = "-1";
						retDetail.respInfo = tmpSbMsg.toString();
					}
				} catch (Exception e) {
					retDetail.respCode = "-1";
					retDetail.respInfo = e.getMessage();

					WriteBankLogLn2(e.getMessage());
				}
			}
		} else {
			retDetail.respCode = "-1";
			retDetail.respInfo = tradeRequestXml.getErrMsg();
		}

		if (retDetail.respCode.equals("-1")	&& StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
			retDetail.reqSeqID = p_req9108.singleDetail.askNumber;
		}

		retAts.writeRetDetail(retDetail);
		return retAts;
	}

	@Override
	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
		RetAtsSglDetail retDetail = new RetAtsSglDetail();

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
			if (actItem == null) {
				retDetail.respCode = "-1";
				retDetail.respInfo = "未找到账号[" + p_req9144.recAct + "]商户配置信息";
				retAts.writeRetDetail(retDetail);
				return retAts;
			}
		
			SingleQueryRequest singleQueryRequest = new SingleQueryRequest();
			singleQueryRequest.setVersion("6.0");
			singleQueryRequest.setInputCharset(getCharset());
			singleQueryRequest.setSignType("MD5");
			singleQueryRequest.setCustomerNo(actItem.merchantId);
			singleQueryRequest.setPayDate(Format.Date8Format.format(p_req9144.getBgnDateTime()));
			singleQueryRequest.setOrderNo(p_req9144.askNumber);
			singleQueryRequest.setSerialNo("");

			VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();
			TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler.creatRequestXml(singleQueryRequest, actItem.saltKey, getCharset(), TradeCodeEnum.SINGLE_QUERY.getCode());

			WriteBankLogLn2("微保单笔实时收款加密前明文:\r\n" + tradeRequestXml.getOriRequestXml());
			WriteBankLogLn2("微保单笔实时收款请求数据:\r\n" + tradeRequestXml.getRequestXml());

			if (tradeRequestXml.getErrMsg() == null) {
				String postURL = bankFront.getUrl("9144");
				WriteBankLogLn2("单笔实时收款查询服务地址:" + postURL);

				String returnDKRecxml = vbaoChargeSystemHandler.http(postURL, tradeRequestXml.getRequestXml(), getCharset());
				WriteBankLogLn2("微保单笔实时收款查询响应数据:\r\n" + returnDKRecxml);

				if (returnDKRecxml != null) {
					String returnOriDKRecxml = Base64vbao.decode(returnDKRecxml, getCharset());
					//returnOriDKRecxml = new String(returnOriDKRecxml.getBytes("GBK"),getCharset());
					
					/*
					try{
						byte[] b1 = Base64Helper.decode(returnDKRecxml);
						if(b1.length>40){//returnOriDKRecxml.contains("<ErrCode>A2001</ErrCode>")
							String s1 = new String(b1, 40,b1.length-40,getCharset());
							byte[] b2 = Base64Helper.decode(s1);
							returnOriDKRecxml = new String(b2,getCharset());
						}
					}catch(Exception e1){
						this.WriteBankLogLn(e1);
					}
					*/
					
					WriteBankLogLn2("微保实时代扣查询解密后明文:\r\n" + returnOriDKRecxml);

					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(returnOriDKRecxml, tmpSbMsg);

					if (tmpBkReader != null) {
						String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
						retDetail.respCode = "0";
						retDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
						retDetail.reqSeqID = p_req9144.askNumber;

						if (tmpReturnCode.equals("T")) {
							retDetail.transAmt = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderAmount");
							retDetail.transState = tmpReturnCode + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode") + "+" + tmpBkReader.getFirstText("/TResponse/OrderInfo/PayStatus");
							retDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
						} else {
							retDetail.transState = tmpReturnCode + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode") + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
							retDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
						}
					} else {
						retDetail.respCode = "-1";
						retDetail.respInfo = tmpSbMsg.toString();
					}
				}
			} else {
				retDetail.respCode = "-1";
				retDetail.respInfo = tradeRequestXml.getErrMsg();
			}
		} catch (Exception e) {
			retDetail.respCode = "-1";
			retDetail.respInfo = e.getMessage();

			e.printStackTrace();

			WriteBankLogLn2(LogHelper.getStackTrace(e));
		}

		if (retDetail.respCode.equals("-1")	&& StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
			retDetail.reqSeqID = p_req9144.askNumber;
		}

		retAts.writeRetDetail(retDetail);
		return retAts;
	}
}
